import { Button, Col, Divider, Form, Input, Row, Select } from 'antd'
import React, { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getCategory } from '../../store/actions/category.action'
import {  GetProductBySearchValue, SearchPayload } from '../../store/actions/product.action'
import { AppState } from '../../store/reducers'
import { CategoryState } from '../../store/reducers/category.reducer'
import { ProductState } from '../../store/reducers/product.reducer'
import ProductItem from './ProductItem'

const Search = () => {
    const categoryState = useSelector<AppState, CategoryState>(state => state.category);
    const productState = useSelector<AppState, ProductState>(state => state.product);
    console.log(productState)
    const dispatch = useDispatch();
    function onFinish(params:SearchPayload) {
        dispatch(GetProductBySearchValue(params))
    }
    useEffect(() => {
        if(!categoryState.category.loaded){
            dispatch(getCategory())
        }
        return () => {
            
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])
   
    return (
        <>
            <Form 
                initialValues={{
                    category:'All'
                }} 
                layout='inline' 
                onFinish={onFinish}
            >
                <Input.Group compact>
                    <Form.Item name='category'>
                        <Select 
                            >
                            <Select.Option value="All">
                                所有分类
                            </Select.Option>
                            {
                                categoryState.category.result.map(item => (
                                    <Select.Option value={item._id} key={item._id}>
                                        {item.name}
                                    </Select.Option>
                                ))
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item name="search">
                        <Input placeholder="搜索"/>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                </Input.Group>
            </Form>   
            <Divider />
            <Row gutter={[16, 16]}>
                <Col span="6">
                    {
                        productState.search.result.map(item => (
                            <ProductItem product={item} key={item._id}/>

                        ))
                    }
                </Col>
            </Row>

        </>
    )
}





export default Search
